<template>
    <div class="layout-container">
        <div class="layout-container-form">
            <div class="layout-container-form-handle">
                <div>
                    <el-switch v-model="modeType"
                        active-text="日" active-value="day" active-color="#13ce66"
                        inactive-text="周" inactive-value="week" inactive-color="#13ce66"
                        @change="draw" />
                </div>
            </div>

            <div class="layout-container-form-search">
                <div>
                    <el-button type="primary" size="small" @click="exportGarden">导出</el-button>
                </div>

                <div>
                    <el-date-picker v-model="queryParam.startDate" type="date" placeholder="开始" value-format="YYYY-MM-DD" />
                </div>
                <div>
                    <el-date-picker v-model="queryParam.endDate" type="date" placeholder="结束" value-format="YYYY-MM-DD" />
                </div>

                <div>
                    <el-button type="primary" :icon="Search" @click="loadData">搜索</el-button>
                </div>
            </div>
        </div>

        <div ref="dom" class="chart" />

        <div class="table-box">
            <el-table ref="table" class="table-show" border :data="[sourceMap.allCount]" height="100%" size="small">
                <el-table-column prop="allCount" label="总计" align="center" />
                <el-table-column prop="dianping" label="点评" align="center" />
                <el-table-column prop="qunaer" label="去哪" align="center" />
                <el-table-column prop="ctrip" label="携程" align="center" />
                <el-table-column prop="tongcheng" label="同程" align="center" />
            </el-table>
        </div>
    </div>
</template>

<script setup lang="ts">
import type {Ref}                                                                                                from 'vue'
import {onActivated, reactive, ref}                                                                              from 'vue'
import {useEventListener}                                                                                        from '@vueuse/core'
import * as echarts                                                                                              from 'echarts/core'
import {CanvasRenderer}                                                                                          from 'echarts/renderers'
import {LineChart}                                                                                               from 'echarts/charts'
import {DataZoomComponent, GridComponent, MarkAreaComponent, TitleComponent, ToolboxComponent, TooltipComponent} from 'echarts/components'
import {UniversalTransition}                                                                                     from "echarts/features";
import {gardenExport, statistics as getStatistics}                                                               from "@/api/garden";
import router                                                                                                    from "@/router";
import {Search}                                                                                                  from '@element-plus/icons-vue'
import fileSaver                                                                                                 from "file-saver";

const dom: Ref<HTMLDivElement> = ref(null) as any

let myEchart: echarts.ECharts | null = null

// 导出
function exportGarden() {
    try {
        gardenExport([queryParam]).then(res => {
            let bstr  = window.atob(res.data);
            let n     = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            let file = new File([u8arr], options.title.text + ".xls", {type: 'application/vnd.ms-excel'});

            fileSaver.saveAs(file)
        })
    } catch (e) {
        console.error(e)
    }
}

// 使用Echart
function useEchart() {
    return new Promise((resolve) => {
        echarts.use([
            TitleComponent, ToolboxComponent, TooltipComponent,
            GridComponent, DataZoomComponent, LineChart,
            CanvasRenderer, UniversalTransition, MarkAreaComponent
        ]);
        myEchart = echarts.init(dom.value)
        useEventListener("resize", () => myEchart!.resize())
        resolve("ok")
    })
}

// 原始数据
const sourceMap: any = ref({
    allCount: {}, // 每个站点的统计数

    dayAreaList    : [], // 天异常区域
    dayAllCountList: [], // 每天 所有站点的数据

    weekAreaList    : [], // 周异常区域
    weekAllCountList: [], // 每周 所有站点的数据
})

const queryParam: any = reactive({
    gardenId : null,
    startDate: null,
    endDate  : null,
})

// 加载数据
function loadData() {
    return new Promise((resolve) => {
        getStatistics(queryParam).then(res => {
            sourceMap.value = res?.data
        }).then(dealArr).then(draw).then(resolve)
    })
}


// 缓存的日数据
const dayShow: any = {
    xKey    : [],
    xdata   : [],
    areaData: [],
}

// 缓存的周数据
const weekShow: any = {
    xKey    : [],
    xdata   : [],
    areaData: [],
}

// 缓存数据
function dealArr() {
    return new Promise((resolve) => {
        dayShow.areaData = sourceMap.value.dayAreaList
        dayShow.xKey     = sourceMap.value.dayAllCountList.map((one: any) => one.date)
        dayShow.xdata    = sourceMap.value.dayAllCountList.map((one: any) => {
            if (one.isAnomaly) {
                one.symbol     = "circle"
                one.symbolSize = 10
                one.itemStyle  = {
                    color: "#ff0000",
                }
            }
            return one
        })

        weekShow.areaData = sourceMap.value.weekAreaList
        weekShow.xKey     = sourceMap.value.weekAllCountList.map((one: any) => one.weekEnd)
        weekShow.xdata    = sourceMap.value.weekAllCountList.map((one: any) => {
            if (one.isAnomaly) {
                one.symbol     = "circle"
                one.symbolSize = 10
                one.itemStyle  = {
                    color: "#ff0000",
                }
            }
            return one
        })
        resolve("ok")
    })
}

// 图标参数
const options = {
    tooltip : {
        trigger : 'axis',
        position: function (pt: any) {
            return [pt[0], '10%'];
        }
    },
    title   : {
        left: 'center',
        text: '公园'
    },
    toolbox : {
        feature: {
            dataZoom   : {
                yAxisIndex: 'none'
            },
            restore    : {},
            saveAsImage: {}
        }
    },
    xAxis   : {
        type       : 'category',
        boundaryGap: false,
        axisLabel  : {},
        data       : [] // 横坐标
    },
    yAxis   : {
        type       : 'value',
        alignTicks : true,
        boundaryGap: [0, '100%'],
        max        : 'dataMax', //取最大值为最大刻度
    },
    dataZoom: [
        {
            type : 'inside',
            start: 0,
            end  : 100
        },
        {
            start: 0,
            end  : 20
        }
    ],
    series  : [
        {
            name         : "",
            showAllSymbol: true,
            type         : 'line',
            smooth       : false,
            symbol       : 'none',
            data         : [],
            markArea     : {
                itemStyle: {
                    color: 'rgba(255, 173, 177, 0.4)'
                },
                data     : []
            }
        }
    ]
}

// 模式类型:week day
const modeType = ref("week")

// 绘图
function draw() {
    return new Promise((resolve) => {
        if (modeType.value === "day") {
            options.xAxis.data              = dayShow.xKey
            options.series[0].data          = dayShow.xdata
            options.series[0].markArea.data = dayShow.areaData
        }
        if (modeType.value === "week") {
            options.xAxis.data              = weekShow.xKey
            options.series[0].data          = weekShow.xdata
            options.series[0].markArea.data = weekShow.areaData
        }

        myEchart?.setOption(options, true)
        resolve("ok")
    })
}

// 初始化
function initParam() {
    return new Promise((resolve) => {
        queryParam.gardenId = router.currentRoute.value.query.gardenId || null

        let gardenName: any = router.currentRoute.value.query.gardenName || ""
        options.title.text  = gardenName
        resolve("ok")
    })
}

// --------------------------- 生命函数 ---------------------------
onActivated(() => {
    initParam().then(useEchart).then(loadData)
})

</script>

<style lang="scss" scoped>
.chart {
    width: 100%;
    height: 80%;
    background: #fff;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
}

.table-box {
    width: 100%;
    height: 10%;
    display: flex;
    justify-content: center;

    .table-show {
        width: 80%;
    }
}
</style>
